package com.multithread.base.impl;

import com.multithread.base.Consumer;
import com.multithread.base.Producer;
import com.multithread.base.Queue;
import com.multithread.base.Scene;

/**
 * @author: hfxiang
 * @Description: 一个生产者 一个消费者 一个队列（也不会设置多个队列吧？）;
 * @date: 2022/7/22 11:27
 */
public class SceneImpl implements Scene {
    Queue queue ;
    Producer producer;
    Consumer consumer;
    public SceneImpl(int size){
        queue = new QueueBlock(size);
        this.producer = new Producer(queue) {
        };
        this.consumer =new Consumer(queue); ;
    }

    public void startWork(final int productNum) {
        Thread threadP = new Thread(producer);
        Thread threadC = new Thread(consumer);
//        Thread threadC2 = new Thread(consumer);

        threadP.start();
        threadC.start();
//        threadC2.start();
        //viewThreadState( threadP, threadC);
        //如果不join的话，junit测试会直接结束主线程，子线程也执行不下去，用Main来开始则不会有这个问题
        try {
            threadP.join();
            threadC.join();
//            threadC2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }

    private void viewThreadState(Thread threadP,Thread threadC){
        while (true){
            try {
                synchronized (this){
                    wait(2000);
                }
                String stateP = threadP.getState().toString();
                String stateC = threadC.getState().toString();
                System.out.println("生产者线程状态："+stateP);
                System.out.println("消费者线程状态："+stateC);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
